package com.atom.module.mvvm.extren

import android.widget.EditText
import androidx.annotation.CheckResult
import androidx.preference.EditTextPreference
import androidx.preference.Preference
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate


@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
fun EditTextPreference.editTextBindEvents() = callbackFlow<EditTextBindEvent> {
    checkMainThread()
    val listener = EditTextPreference.OnBindEditTextListener {
        trySend(EditTextBindEvent(it))
    }
    setOnBindEditTextListener(listener)
    awaitClose { setOnBindEditTextListener(null) }
}.conflate()

data class EditTextBindEvent(public val editText: EditText)

@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
fun Preference.preferenceChanges() = callbackFlow<Any> {
    checkMainThread()
    val listener = Preference.OnPreferenceChangeListener { _, newValue ->
        trySend(newValue)
        true
    }
    onPreferenceChangeListener = listener
    awaitClose { onPreferenceChangeListener = null }
}.conflate()

@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
fun Preference.preferenceClicks() = callbackFlow<Unit> {
    checkMainThread()
    val listener = Preference.OnPreferenceClickListener {
        trySend(Unit)
        true
    }
    onPreferenceClickListener = listener
    awaitClose { onPreferenceClickListener = null }
}.conflate()